<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    body {
      margin: 0;
    }
    
    canvas {
      display: block;
    }

  </style>
</head>
<body>
  <canvas></canvas>

  <script>
    var canvas = document.querySelector('canvas')
    var 
      width = window.innerWidth,
      height = window.innerHeight
    canvas.width = width
    canvas.height = height

    var ctx = canvas.getContext('2d')

    function random (x, y) {
      return Math.floor(Math.random() * (y - x)) + x
    }

    function Ball () {
      var r = random(5, 10)
      this.r = r
      this.x = random(r, width - r)
      this.y = random(r, height - r)
      this.sx = Math.random() > 0.5 ? -0.1 : 0.1
      this.sy = Math.random() > 0.5 ? -0.1 : 0.1
    }

    function drawBall (balls) {
      for (var i = 0;i < balls.length; i++) {
        var ball = balls[i]
        ctx.beginPath()
        ctx.fillStyle = 'rgba(200,200,200,.8)'
        ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI)
        ctx.fill()
        ctx.closePath()
      }
    }

    function move (balls) {
      for (var i = 0; i < balls.length; i++) {
        var ball = balls[i]
        if (ball.x >= width - ball.r || ball.x <= ball.r) {
          ball.sx = -ball.sx
        }

        if (ball.y >= height - ball.r || ball.y <= ball.r) {
          ball.sy = -ball.sy
        }

        ball.x += ball.sx
        ball.y += ball.sy
      }
    }

    var balls = []
    for (var i = 0; i < 10; i++) {
      balls.push(new Ball())
    }


    console.log(balls)
    drawBall(balls)
    setInterval(function () {
      ctx.clearRect(0, 0, width, height)
      move(balls)
      drawLine(balls)
      drawBall(balls)
    }, 1000 / 60)

    function drawLine (balls) {
      // 连线
    for (var i = 0; i < balls.length - 1; i++) {
      console.log('--------------------------')
        console.log('参照球' + (i + 1))
        for (var j = i + 1; j < balls.length; j++) {
          // balls[i] balls[j]
          var x = Math.sqrt(Math.pow(balls[i].x - balls[j].x, 2) + Math.pow(balls[i].y - balls[j].y, 2))
          console.log('对比球' + (j + 1) + ',距离为' + x)
          if (x <= 500) {
            ctx.beginPath()
            var a = 1 - x / 500 * 0.8
            ctx.strokeStyle = 'rgba(200, 200, 200, ' + a + ')'
            ctx.moveTo(balls[i].x, balls[i].y)
            ctx.lineTo(balls[j].x, balls[j].y)
            ctx.stroke()
            ctx.closePath()
          }
          
        }
        console.log('-------------------')
      }
    }
    

  
  </script>
</body>
</html>